﻿using System;
using System.IO;
using System.ServiceModel;
using System.Collections.Generic;
using System.Diagnostics;
using ajayumi.develop.win32.Transport.WCF.Services;
using ajayumi.develop.win32.Transport.Core;
using ajayumi.develop.win32.Transport.Utils;
using System.Collections.Concurrent;

namespace ajayumi.develop.win32.Transport.AppUpgrade.Controls
{
    public partial class UcDownloading : UcBase
    {

        #region Properties

        private UpgradeFileCollection m_UpgradeFileCollection = null;
        private List<FilePathInfo> m_UpgradeFiles = null;
        private List<string> m_SetupFiles = null;

        #endregion

        public UcDownloading()
        {
            InitializeComponent();
        }

        public UcDownloading(UcBase preControl)
            : base(preControl)
        {
            InitializeComponent();
        }

        protected override void InitDefaultValue()
        {
            base.InitDefaultValue();

            this.Title = "下载升级文件";
        }

        internal override UcBase Next()
        {
            return new UcUpdating(this)
            {
                UpgradeDir = Utility.GetDownloadDir()
            };
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            this.SetButtonVisible(WizardFormButtons.Exit);

            this.m_UpgradeFiles = new List<FilePathInfo>();

            ArgumentSerialization.AppLatestVersion = Program.UpgradeInfo.Version;

            if (ArgumentSerialization.IsFullUpgrade)
            {
                //foreach (FilePathInfo item in Program.UpgradeInfo.FullUpgradeFiles)
                //{
                //    this.m_UpgradeFiles.Add(item);
                //}
                this.m_UpgradeFiles.AddRange(Program.UpgradeInfo.FullUpgradeFiles);
            }
            else
            {
                //foreach (FilePathInfo item in Program.UpgradeInfo.DiffUpgradeFiles)
                //{
                //    this.m_UpgradeFiles.Add(item);
                //}
                this.m_UpgradeFiles.AddRange(Program.UpgradeInfo.DiffUpgradeFiles);
            }

            if (this.m_UpgradeFiles.Count <= 0)
            {
                this.Completed();
                return;
            }

            this.m_UpgradeFileCollection = new UpgradeFileCollection(this.m_UpgradeFiles.Count);
            this.m_SetupFiles = new List<string>();
            this.dgvFiles.AutoGenerateColumns = false;
            this.dgvFiles.DataSource = this.m_UpgradeFileCollection;
            this.DoWork();
        }

        private void DoWork()
        {
            DownloadFile downloadFile = null;
            TransFileItem transFileItem = null;

            TransportFileServiceClient client = new TransportFileServiceClient();

            //List<string> setupList = new List<string>();
            foreach (FilePathInfo item in this.m_UpgradeFiles)
            {
                downloadFile = new DownloadFile(item.RootPath, item.RelativePath,
                                     (file) => { return client.InitDownloadFile(file); },
                                     (file) => { return client.DownloadFile(file); });
                downloadFile.SaveDirectoryFunc = Utility.GetDownloadDir;
                downloadFile.TransReady += (sender, e) =>
                {
                    this.m_UpgradeFileCollection.TransFileReady(e.RelativePath,
                        FileHelper.FormatFileSize(e.FileLength),
                        e.ProgressPercentage);
                };
                downloadFile.TransProgressChanged += (sender, e) =>
                {
                    this.m_UpgradeFileCollection.TransFileProgressChanged(e.RelativePath, e.ProgressPercentage);
                };
                downloadFile.TransCompleted += downloadFile_TransCompleted;
                //(sender, e) =>
                //{
                //    this.m_UpgradeFileCollection.TransFileCompleted(e);
                //    setupList.Add(e.FullPath);

                //    // 判断所有升级是否下载完成
                //    if (this.m_UpgradeFileCollection.IsCompleted)
                //    {
                //        switch (Program.UpgradeInfo.UpgradeMode)
                //        {
                //            case UpgradeMode.CompressionPackage:
                //                break;
                //            case UpgradeMode.InstallationPackage:
                //                foreach (string s in setupList)
                //                {
                //                    Process.Start(s);
                //                }
                //                ArgumentSerialization.Save();
                //                System.Environment.Exit(System.Environment.ExitCode);
                //                break;
                //            case UpgradeMode.Normal:
                //            default:
                //                this.PerformNext();
                //                break;
                //        }
                //    }
                //    setupList.Clear();
                //};

                transFileItem = new TransFileItem()
                {
                    Name = Path.GetFileName(item.FullPath),
                    RelativePath = item.RelativePath
                };
                this.m_UpgradeFileCollection.Add(transFileItem);

                downloadFile.RunWorkAsync();
            }

        }

        void downloadFile_TransCompleted(object sender, TransCompletedEventArgs e)
        {
            this.m_UpgradeFileCollection.TransFileCompleted(e);
            this.m_SetupFiles.Add(e.FullPath);

            // 判断所有升级是否下载完成
            if (this.m_UpgradeFileCollection.IsCompleted)
            {
                this.Completed();
            }
            this.m_SetupFiles.Clear();
        }

        /// <summary>
        /// 完成
        /// </summary>
        private void Completed()
        {
            switch (Program.UpgradeInfo.UpgradeRunMode)
            {
                case UpgradeRunMode.InstallationPackage:
                    foreach (string s in this.m_SetupFiles)
                    {
                        Process.Start(s);
                    }
                    ArgumentSerialization.Save();
                    System.Environment.Exit(System.Environment.ExitCode);
                    return;
                case UpgradeRunMode.CompressionPackage:
                case UpgradeRunMode.Normal:
                default:
                    this.PerformNext();
                    break;
            }
        }


    }
}
